package com.example.androidutils.base;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.androidutils.R;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity {

    private RelativeLayout mBaseLayout;
    private RelativeLayout header_back_btn;
    private FrameLayout mFraLayoutContent;
    private RelativeLayout mLayoutHeadView;
    private RelativeLayout mErrorLayout;
    private ImageView mHeaderLeftImg;
    private TextView mHeaderTitle;
    private ImageView mHeaderRightImg;
    private Toast mToast;
    private LinearLayout mBaseSearchHeader;
    private FrameLayout mBaseHeader;
    private TextView mRetryTitle;
    private TextView mRetryBtn;
    Unbinder unbinder;
    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;
    protected ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
//        TaijiApplication.mInstance().addActivity(this);
        mBaseLayout = (RelativeLayout) findViewById(R.id.relLayoutBase);
        mFraLayoutContent = (FrameLayout) findViewById(R.id.fraLayoutContent);
        mBaseHeader = (FrameLayout) findViewById(R.id.base_header);
        mLayoutHeadView = (RelativeLayout) findViewById(R.id.base_header_layout);
        mErrorLayout = (RelativeLayout) findViewById(R.id.base_error_layout);
        header_back_btn = (RelativeLayout) findViewById(R.id.header_back_btn);
        mHeaderLeftImg = (ImageView) findViewById(R.id.header_left_img);
        mHeaderTitle = (TextView) findViewById(R.id.header_title);
        mHeaderRightImg = (ImageView) findViewById(R.id.header_right_img);

        mRetryBtn = (TextView) findViewById(R.id.view_error_retry);
//        mRetryTitle = (TextView) findViewById(R.id.view_error_title);


        if (getLayoutId() != -1) {
            LayoutInflater.from(this).inflate(getLayoutId(), mFraLayoutContent, true);
        }


        unbinder = ButterKnife.bind(this, mFraLayoutContent);
        initView();
        initListener();
        initData();
        if (isImmersionBarEnabled())
            initImmersionBar();

        mRetryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onRetryBtnClick();
            }
        });
        mHeaderLeftImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onHeaderLeftClicked();
            }
        });
        mHeaderRightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onHeaderRightClicked();
            }
        });
//        mBaseSearchHeader.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                onSearchHeaderClicked();
//            }
//        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);


    }

    protected void setRetryText(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            mRetryTitle.setText(msg);
        }
    }

    public void toggleBaseHeader(boolean tg) {
        if (tg) {
            mBaseHeader.setVisibility(View.VISIBLE);
        } else {
            mBaseHeader.setVisibility(View.GONE);
        }
    }

//    public void setHeaderStyleSearch() {
//        mBaseSearchHeader.setVisibility(View.VISIBLE);
//        mLayoutHeadView.setVisibility(View.GONE);
//        mHeaderStyle = true;
//        ImmersionBar.with(this)
//                .titleBar(mBaseSearchHeader, false)
//                .addTag(Constants.TOOLBAR_STYLE_SEARCH)
//                .init();
//    }

//    public void setHeaderStyleNormal() {
//        mBaseSearchHeader.setVisibility(View.GONE);
//        mLayoutHeadView.setVisibility(View.VISIBLE);
//        mHeaderStyle = false;
//    }

    public void setHeaderColor(int color) {
        mLayoutHeadView.setBackgroundColor(color);
    }

    public void setHeaderTitle(int resId) {
        mHeaderTitle.setText(getString(resId));
    }

    public void setHeaderTitle(String title) {
        mHeaderTitle.setText(title);
    }

    protected void toggleHeaderRightBtn(boolean visible) {
        if (visible) {
            mHeaderRightImg.setVisibility(View.VISIBLE);
        } else {
            mHeaderRightImg.setVisibility(View.GONE);
        }

    }

    protected void headerBackBtn(boolean visible) {
        if (visible) {
            header_back_btn.setVisibility(View.VISIBLE);
        } else {
            header_back_btn.setVisibility(View.GONE);
        }

    }


    protected void onHeaderLeftClicked() {
        finish();
    }

    protected void onHeaderRightClicked() {

    }

    protected void onSearchHeaderClicked() {

    }

    @Override
    public void onBackPressed() {
        onHeaderLeftClicked();
    }

    protected void toggleErrorLayout(boolean tg) {
        if (tg) {
            mErrorLayout.setVisibility(View.VISIBLE);
        } else {
            mErrorLayout.setVisibility(View.GONE);
        }
    }

    protected void headerVisible(boolean tg) {
        if (tg) {
            mLayoutHeadView.setVisibility(View.VISIBLE);
        } else {
            mLayoutHeadView.setVisibility(View.GONE);
        }
    }

    protected void setHeaderLeftImg(int resId) {
        mHeaderLeftImg.setImageResource(resId);
    }

    protected void setHeaderRightImg(int resId) {
        mHeaderRightImg.setImageResource(resId);
    }


    public void jumpActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void jumpActivityForResult(Class<?> clz, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    public void jumpActivity(Class<?> clz) {
        jumpActivity(clz, null);
    }

    public void jumpActivityClearTask(Class<?> clz) {
        Intent intent = new Intent(this, clz);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

//    public CommonPopupWindow createPop(CommonPopupWindow.Builder builder, boolean createNew) {
//        if (popupWindow == null) {
//            popupWindow = builder.create();
//        } else {
//            if (createNew) {
//                dismissPop();
//                popupWindow = builder.create();
//            }
//        }
//        return popupWindow;
//    }
//
//    public void showPop(int gravity) {
//        if (popupWindow != null && !popupWindow.isShowing()) {
//            popupWindow.showAtLocation(mBaseLayout, gravity, 0, 0);
//        }
//    }
//
//    public void showPopPos(int[] pos) {
//        if (popupWindow != null && !popupWindow.isShowing()) {
//            popupWindow.showAtLocation(mBaseLayout, Gravity.END | Gravity.TOP, pos[0], pos[1]);
//        }
//    }
//
//    protected void showPopDropDown(View view) {
//        if (popupWindow != null && !popupWindow.isShowing()) {
//            popupWindow.showAsDropDown(view);
//        }
//    }
//
//    public void dismissPop() {
//        if (popupWindow != null && popupWindow.isShowing()) {
//            popupWindow.dismiss();
//        }
//    }

    protected void showToast(int resId) {
        showToast(getResources().getString(resId));
    }

    protected void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    @Override
    protected void onResume() {
        super.onResume();

//        MobclickAgent.onResume(this);友盟
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);友盟

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        TaijiApplication.mInstance().removeActivity(this);
        unbinder.unbind();
        unregisterReceiver(networkChangeReceiver);
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    /**
     * 沉浸式状态初始化
     */
    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.with(this)
                .titleBar(mLayoutHeadView, false)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    protected int getResColor(@ColorRes int colorId) {
        if (Build.VERSION.SDK_INT >= 23) {
            return this.getColor(colorId);
        } else {
            return getResources().getColor(colorId);
        }
    }

    protected abstract int getLayoutId();

    protected void initView() {
    }

    protected void initData() {
    }

    protected void initListener() {
    }

    protected void onLeftBtnClick() {
    }

    protected void onRetryBtnClick() {
    }


    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
//                Toast.makeText(context, "当前网络可用", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
            }

        }
    }


    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

}

